<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      size="small"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="植物名称" prop="plantName">
        <el-input
          v-model="queryParams.plantName"
          placeholder="请输入植物名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="绿化范围" prop="greenAreaId">
        <el-select
          clearable
          v-model="queryParams.greenAreaId"
          placeholder="请选择绿化范围"
        >
          <el-option
            v-for="item in buiGreenAreaListAll"
            :key="item.id"
            :label="item.areaScope"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="园区" prop="parkId">
        <el-select
          clearable
          v-model="queryParams.parkId"
          @change="getBuildingList(form.parkId)"
          placeholder="请选择园区"
        >
          <el-option
            v-for="item in buiParkList"
            :key="item.id"
            :label="item.parkNum"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索
        </el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置
        </el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['park:wyGreenInfo:add']"
        >新增
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['park:wyGreenInfo:edit']"
        >修改
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['park:wyGreenInfo:remove']"
        >删除
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['park:wyGreenInfo:export']"
        >导出
        </el-button
        >
      </el-col>


      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleImport"
          v-hasPermi="['park:wyGreenInfo:import']"
        >导入
        </el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="addPlantType()"
          v-hasPermi="['park:wyGreenInfo:add']"
        >新增植物种类
        </el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>


    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <!--<el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据-->
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>


    <el-table
      v-loading="loading"
      :data="wyGreenInfoList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="植物名称" align="center" prop="plantName"/>
      <el-table-column label="数量" align="center" prop="amount"/>
      <!--      <el-table-column label="面积(m²)" align="center" prop="area" />-->
      <el-table-column label="绿化范围" align="center" prop="areaName"/>
      <el-table-column label="园区" align="center" prop="parkNum"/>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['park:wyGreenInfo:edit']"
          >修改
          </el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['park:wyGreenInfo:remove']"
          >删除
          </el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改绿化信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div style="position:absolute;right: 20px;z-index: 2;margin-top: 1px;" v-if="this.form.id == null">
          <el-button
            icon="el-icon-plus"
            size="mini"
            type="primary"
            @click="addPlants()"
          ></el-button>
        </div>
        <template v-if="this.form.id == null">
          <div v-for="(item,index) in form.addList" :key="index" class="plant-item" >
            <el-button
              v-if="index!=0"
              icon="el-icon-minus"
              size="mini"
              type="primary"
              @click="lessPlants(index)"
            ></el-button>
            <el-form-item label="植物名称" prop="plantName">
              <el-select v-model="item.plantName" filterable>
                <el-option :value="item2.dictLabel" :label="item.dictLabel" v-for="(item2,index2) in plants"
                           :key="index2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="数量" prop="amount">
              <el-input v-model.number="item.amount" type='number' placeholder="请输入数量"/>
            </el-form-item>
          </div>
        </template>
        <template v-else>
          <el-form-item label="植物名称" prop="plantName">
            <el-select v-model="form.plantName" filterable>
              <el-option :value="item.dictLabel" :label="item.dictLabel" v-for="(item,index) in plants"
                         :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="数量" prop="amount">
            <el-input v-model.number="form.amount" type='number' placeholder="请输入数量"/>
          </el-form-item>
        </template>


        <el-form-item label="园区" prop="parkId">
          <el-select
            clearable
            v-model="form.parkId"
            @change="getBuildingList(form.parkId)"
            placeholder="请选择园区"
          >
            <el-option
              v-for="item in buiParkList"
              :key="item.id"
              :label="item.parkNum"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="绿化范围" prop="greenAreaId">
          <el-select
            clearable
            v-model="form.greenAreaId"
            placeholder="请选择绿化范围"
          >
            <el-option
              v-for="item in buiGreenAreaList"
              :key="item.id"
              :label="item.areaScope"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <!--        <el-form-item label="面积" prop="area">-->
        <!--          <el-input v-model.number="form.area" type='number' placeholder="请输入面积" />-->
        <!--        </el-form-item>-->


        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listWyGreenInfo,
  getWyGreenInfo,
  delWyGreenInfo,
  addWyGreenInfo,
  updateWyGreenInfo,
} from "@/api/smartParks/property/ropertyPlant";
import {listBuiPark} from "@/api/parkAssets/enterCommunity";
import {listBuiGreenArea} from "@/api/parkAssets/buildingGreening";
import { getToken } from '@/utils/auth'
import { getBuiRoom } from '@/api/parkAssets/buildingRoom'

export default {
  name: "WyGreenInfo",
  components: {},
  data() {
    return {

      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/park/wyGreenInfo/importData"
      },

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      buiParkList: [],
      buiGreenAreaList: [],
      buiGreenAreaListAll: [],
      // 绿化信息表格数据
      wyGreenInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        plantName: null,
        amount: null,
        area: null,
        greenAreaId: null,
        parkId: null,
      },
      // 表单参数
      form: {
        addList: [
          {
            plantName: '',
            amount: 1
          }
        ]
      },
      plants: [],
      // 表单校验
      rules: {
        // area: [{ required: true, message: "面积不能为空", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getList();
    listBuiPark().then((response) => {
      this.buiParkList = response.rows;
    });
    listBuiGreenArea().then((response) => {
      this.buiGreenAreaListAll = response.rows;
    });
    this.getDicts('plants').then(res => {
      this.plants = res.data
    })
  },
  methods: {
    //得到楼栋
    getBuildingList(value) {
      this.form.greenAreaId = "";
      listBuiGreenArea({parkId: value}).then((response) => {
        this.buiGreenAreaList = response.rows;
      });
    },
    /** 查询绿化信息列表 */
    getList() {
      this.loading = true;
      listWyGreenInfo(this.queryParams).then((response) => {
        this.wyGreenInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },


    /** 下载模板操作 */
    importTemplate() {
      if (this.tempType == 0) {
        this.download('park/wyGreenInfo/importTemplate', {
          ...this.queryParams
        }, `绿化导入模板.xlsx`)
      }
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '绿化导入'
      this.upload.open = true
      this.tempType = 0
    },


    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (this.tempType == 0){
        this.upload.open = false
        this.upload.isUploading = false
        this.$refs.upload.clearFiles()
      }
      this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true })
      this.getList();
    },

    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    filePopClose(){
      this.showFilePop=false
    },
    showFileDowFn(row){
      this.reset();
      const id = row.id || this.ids;
      getBuiRoom(id).then((response) => {
        response.data.fileList.forEach((element) => {
          let url= "http://" + element.url
          this.fileList.push({
            name: element.name,
            id: element.id,
            url,
          })
        });
      });
      this.showFilePop=true
    },



    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        plantName: null,
        amount: null,
        area: null,
        greenAreaId: null,
        parkId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        addList: [{
          plantName: '',
          amount: 1
        }]
      };
      this.resetForm("form");
    },
    addPlants() {
      this.form.addList.push({
        plantName: '',
        amount: 1
      })
    },
    lessPlants(index) {
      this.form.addList.splice(index, 1)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加绿化信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getWyGreenInfo(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改绿化信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateWyGreenInfo(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            let reqData = []
            this.form.addList.forEach(item => {
              let obj = {}
              obj.plantName = item.plantName
              obj.amount = item.amount
              obj.parkId = this.form.parkId
              obj.greenAreaId = this.form.greenAreaId
              reqData.push(obj)
            })
            addWyGreenInfo(reqData).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("是否确认删除绿化信息的数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delWyGreenInfo(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "park/wyGreenInfo/export",
        {
          ...this.queryParams,
        },
        `park_wyGreenInfo.xlsx`
      );
    },
    // 添加植物总类
    addPlantType(){
      this.$router.push('/dict/type/data/93')
    }
  },
};
</script>
<style lang="scss">
.plant-item {
  position: relative;

  .el-button {
    position: absolute;
    right: 0;
    top: 0;
    z-index: 2;
    margin-top: 1px;
  }
}
</style>
